package com.huaxin.common;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.huaxin.common.cache.ACache;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.StringUtils;
import com.huaxin.common.utils.Util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by hebing on 2016/3/30.
 */
public abstract class BaseFragment extends Fragment {

    protected final static String TAG          = "BaseFragment";
    public                 View   mContentView = null;
    protected LayoutInflater mInflater;
    protected View           mView;
    private   Unbinder       unbinder;
    private   RequestManager mGlide;
    protected static final int LOADING      = 0x0101;//加载界面
    protected static final int LOAD_ERROR   = LOADING + 1;//加载错误
    protected static final int LOAD_SUCCESS = LOADING + 2;//加载成功
    public static final    int LOAD_FAILURE = LOADING + 3;//加载失败
    public static final    int LOAD_NO_DATA = LOADING + 4;//无数据
    private View fl_failure, fl_loading, fl_no_data;
    private ACache mACache;
    private Gson   mGson;

    //
    protected boolean isInit = false;
    protected boolean isLoad = false;
    private TextView mTvTip;

    /**
     * more info see
     * {@link BaseActivity#onCreate(Bundle)}
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.mInflater = inflater;
        if (mView == null && getContentViewId() > 0) {
            mView = mInflater.inflate(getContentViewId(), container, false);
            if (getLoadFrameId() != 0) {
                bindLoadView((ViewGroup) mView.findViewById(getLoadFrameId()));
            }
            unbinder = ButterKnife.bind(this, mView);
            init(savedInstanceState);
            initView(mView);
            initData();
            isInit = true;
            isCanLoadData();
            requestData();
        }
        onResumeView();
        return mView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }

    private void isCanLoadData() {
        if (!isInit) {
            return;
        }

        if (getUserVisibleHint()) {
            lazyLoad();
            isLoad = true;
        } else {
            if (isLoad) {
                stopLoad();
            }
        }
    }

    protected void lazyLoad() {
    }

    protected void stopLoad() {
    }

    protected void requestData() {

    }

    /**
     * finish current fragment
     */
    public void finish() {
        getActivity().onBackPressed();
    }

    /**
     * add fl_loading & error view
     */
    protected void bindLoadView(ViewGroup viewGroup) {
        if (fl_failure != null || fl_loading != null || viewGroup == null) {
            return;
        }
        fl_failure = mInflater.inflate(R.layout.static_network_error, viewGroup, false);
        //        viewGroup.addView(fl_failure, new ViewGroup.LayoutParams(-1, -1));////////////////////////此处被改
        fl_loading = mInflater.inflate(R.layout.static_loading, viewGroup, false);
        viewGroup.addView(fl_loading, new ViewGroup.LayoutParams(-1, -1));
        fl_no_data = mInflater.inflate(R.layout.static_no_data, viewGroup, false);
        mTvTip = (TextView) fl_no_data.findViewById(R.id.tv_tip);
        viewGroup.addView(fl_no_data, new ViewGroup.LayoutParams(-1, -1));
        fl_failure.findViewById(R.id.reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestData();
            }
        });
        LinearLayout layout = (LinearLayout) fl_no_data.findViewById(R.id.no_data_ll);
        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestData();
            }
        });
        fl_failure.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        fl_loading.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        //        fl_no_data.setOnTouchListener(new View.OnTouchListener() {
        //            @Override
        //            public boolean onTouch(View v, MotionEvent event) {
        //                return true;
        //            }
        //        });
        //add listener
    }

    protected void updateLoadStatus(int status, String msg) {
        if (fl_failure == null || fl_loading == null) {
            return;
        }
        if (status == LOADING) {
            fl_loading.setVisibility(View.VISIBLE);
            fl_failure.setVisibility(View.GONE);
            fl_no_data.setVisibility(View.GONE);
        } else if (status == LOAD_FAILURE) {
            fl_loading.setVisibility(View.GONE);
            fl_failure.setVisibility(View.GONE);///////////////////////////////此处被改
            fl_no_data.setVisibility(View.GONE);
        } else if (status == LOAD_SUCCESS) {
            fl_loading.setVisibility(View.GONE);
            fl_failure.setVisibility(View.GONE);
            fl_no_data.setVisibility(View.GONE);
        } else if (status == LOAD_ERROR) {
            fl_loading.setVisibility(View.GONE);
            fl_failure.setVisibility(View.GONE);
            if (StringUtils.isEmpty(msg)) {
                ((TextView) fl_no_data.findViewById(R.id.tv_tip)).setText(msg);
            }
            fl_no_data.setVisibility(View.VISIBLE);
        } else if (status == LOAD_NO_DATA) {
            fl_loading.setVisibility(View.GONE);
            fl_failure.setVisibility(View.GONE);
            fl_no_data.setVisibility(View.VISIBLE);
            mTvTip.setText(msg);
        }
    }

    protected void updateLoadStatus(int status) {
        updateLoadStatus(status, null);
    }

    protected void onResumeView() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            final View statusBar = mView.findViewById(R.id.status_bar);
            if (statusBar != null) {
                statusBar.setVisibility(View.GONE);
            }
        }
    }

    protected void autoClose(Object object) {
        if (getActivity() == null)
            return;
        ((BaseActivity) getActivity()).autoClose(object);
    }

    @Override
    public void onDestroy() {
        if (unbinder != null) {
            unbinder.unbind();
        }
        super.onDestroy();
    }

    protected void onBeforeSetContentLayout() {
    }

    protected void initData() {
    }


    protected void initView(View view) {

    }

    protected void init(Bundle savedInstanceState) {

    }


    protected int getContentViewId() {
        return 0;
    }

    public RequestApi getRequestApi() {
        return RequestHelper.getRequestApi();
    }

    /**
     * 媒体文件的下载、缓存、显示、本地加载使用Glide
     *
     * @return
     */
    public synchronized RequestManager getGlide() {
        if (mGlide == null) {
            mGlide = Glide.with(this);
        }
        return mGlide;
    }

    public synchronized ACache getACache() {
        if (mACache == null) {
            mACache = ACache.get(getContext());
        }
        return mACache;
    }

    public synchronized Gson getGson() {
        if (mGson == null) {
            mGson = new Gson();
        }
        return mGson;
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }


    public int getLoadFrameId() {
        return 0;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isInit = false;
        isLoad = false;
    }

    /**
     * 方便Text Image的加载
     */
    public static final int SET_GONE = 0x01;
    public static final int SET_NULL = 0x02;
    public static final int SET_DEF  = 0x03;

    public void loadImg(ImageView imageView, String url, Integer id) {
        if (imageView == null) {
            return;
        }
        if (id != null) {
            Glide.with(this).load(url).apply(new RequestOptions().placeholder(id)).into(imageView);
        } else {
            Glide.with(this).load(url).apply(new RequestOptions().placeholder(Constants
                    .DEFAULT_LOADING_IMG)).into(imageView);
        }
    }

    public void loadNetImg(ImageView imageView, String url) {
        //loadImg(imageView, addHost(url), null);
        loadImg(imageView, url, null);
    }

    public void loadImg(ImageView imageView, String url) {
        loadImg(imageView, url, null);
    }


    Bitmap loadImg(Bitmap bitmap) {
        return bitmap;
    }

    public void loadText(String label, TextView textView, String context, String def, View attach, int type) {
        if (Util.checkNull(textView)) {
            return;
        }
        textView.setVisibility(View.VISIBLE);
        if (!Util.checkNull(context)) {
            textView.setText((label == null ? "" : label) + context);
        } else {
            switch (type) {
                case SET_GONE:
                    if (attach != null) {
                        attach.setVisibility(View.GONE);
                    }
                    textView.setVisibility(View.GONE);
                    break;
                case SET_NULL:
                    textView.setText(null);
                    break;
                case SET_DEF:
                    if (def != null) {
                        textView.setText((label == null ? "" : label) + def);
                    } else {
                        textView.setText((label == null ? "" : label) + "无数据");
                    }

                default:
                    break;
            }

        }
    }


    public void loadText(String label, TextView textView, String context, String def) {
        loadText(label, textView, context, def, null, SET_DEF);
    }

    public void loadText(String label, TextView textView, String context) {
        loadText(label, textView, context, null, null, 0);
    }

    public void loadText(TextView textView, String context, int type) {
        loadText(null, textView, context, null, null, type);
    }

    public void loadText(TextView textView, String context) {
        loadText(textView, context, SET_GONE);
    }

    public void loadText(TextView textView, String context, View attach) {
        loadText(null, textView, context, null, attach, SET_GONE);
    }

    public void loadText(TextView textView, String context, String def) {
        loadText(null, textView, context, def, null, SET_DEF);
    }


    public String dateFormat(Long realStartDate) {
        return dateFormat(realStartDate, "yyyy年MM月dd日");
    }

    public String dateFormat2(Long realStartDate) {
        return dateFormat(realStartDate, "yyyy年MM月dd日 HH:mm:ss");
    }

    public String dateFormat(Long realStartDate, String pattern) {
        if (Util.checkNull(realStartDate)) {
            return null;
        }
        return new SimpleDateFormat(pattern).format(new Date(realStartDate));
    }

    public static String[] addHost(String[] imgNames) {
        for (int i = 0; i < imgNames.length; i++) {
            imgNames[i] = BaseConfig.getFileUrl() + imgNames[i];
        }
        return imgNames;
    }

    public static String addHost(String imgNames) {
        return BaseConfig.getFileUrl() + imgNames;
    }


    /**
     * 获取两个时间串时间的差值，单位为小时
     *
     * @param startTime 开始时间 yyyy-MM-dd HH:mm:ss
     * @param endTime   结束时间 yyyy-MM-dd HH:mm:ss
     * @return 两个时间的差值(秒)
     */
    public static String getDiffHour(long startTime, long endTime) {
        DateFormat df = new SimpleDateFormat("HH:mm:ss");
        long days = 0, hours = 0, minutes = 0;
        try {
            Date d1 = df.parse(df.format(new Date(startTime)));
            Date d2 = df.parse(df.format(new Date(endTime)));
            long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
            days = diff / (1000 * 60 * 60 * 24);
            hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
            minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(TAG, "getDiffHour: -->" + days + "天" + hours + "小时" + minutes + "分");
        return hours + "小时" + minutes + "分";
    }


}
